package main

import "log"

// 单笔查询
func getOne(id int) (app, error) {
	a := app{}
	err := db.QueryRow("SELECT * FROM characters WHERE Id=?", id).Scan(&a.ID, &a.name)
	return a, err
}

// 多笔查询
func getMany(id int) (apps []app, err error) {
	rows, err := db.Query("SELECT * FROM characters WHERE Id<? ORDER BY Id DESC", id)
	if err != nil {
		log.Fatalln(err)
	}
	for rows.Next() {
		a := app{}
		err = rows.Scan(&a.ID, &a.name)
		if err != nil {
			log.Fatalln(err)
		}
		apps = append(apps, a)
	}
	return
}

// 更新
func (a *app) Update() (err error) {
	_, err = db.Exec("UPDATE characters SET Name=? WHERE Id=?", a.name, a.ID)
	return
}

// 删除
func (a *app) Delete() (err error) {
	_, err = db.Exec("DELETE FROM characters WHERE Id=?", a.ID)
	return
}

// 新增
func (a *app) Insert() (err error) {
	sqlStr := `INSERT INTO characters (Name) VALUE (?);`
	stmt, err := db.Prepare(sqlStr)
	if err != nil {
		log.Fatalln(err)
	}
	defer stmt.Close()
	_, err = stmt.Exec(a.name)
	if err != nil {
		log.Fatalln(err)
	}
	// 查询插入数据的id
	err = db.QueryRow("SELECT IFNULL(LAST_INSERT_ID(), -1);").Scan(&a.ID)
	if err != nil {
		log.Fatalln(err)
	}
	return
}
